package com.xinqi.modules.course.clazz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.user.Account;
import com.xinqi.common.core.constant.MQConstants;
import com.xinqi.common.core.enums.*;
import com.xinqi.common.rocketmq.dto.ChatMessageMessageBody;
import com.xinqi.common.rocketmq.dto.CourseClassMessageBody;
import com.xinqi.common.rocketmq.dto.MqMessageDTO;
import com.xinqi.common.rocketmq.event.ProducerEvent;
import com.xinqi.modules.chat.chat.rongyun.RemoteRongyunClient;
import com.xinqi.modules.chat.chat.template.TemplateMessageDTO;
import com.xinqi.modules.course.clazz.dto.rsp.ClassResultDTO;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version V1.0
 * @Title: 课程班级MQ
 * @ClassName: com.xinqi.modules.course.clazz.service.impl.ClassMqService.java
 * @Description:
 * @Copyright 星齐科技（云南）有限公司 - Powered By 技术部
 * @author: yyzhen
 * @date: 2023/8/14 16:06
 */

@Log4j2
@Service("classMqService")
@RequiredArgsConstructor
public class ClassMqService {

    private final RemoteRongyunClient remoteRongyunClient;

    /**
     * 课程转让
     *
     * @param classId
     * @param studentId
     */

    public void courseTransfer(Long classId, Long studentId) {
        CourseClassMessageBody body = new CourseClassMessageBody();
        body.setType(RocketMqCourseEnum.COURSE_TRANSFER.getCode());
        body.setClassId(classId);
        body.setStudentId(studentId);
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.COURSE_SYNC.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.CLASS_MESSAGE_KEY + classId);
        ProducerEvent.producerFifoMessage(message);
    }


    /**
     * 成员身份却换
     *
     * @param classId
     * @param studentId
     * @param switchType
     */

    public void studentIdentitySwitch(Long classId, Long studentId, StudentSwitchType switchType) {
        CourseClassMessageBody body = new CourseClassMessageBody();
        body.setType(RocketMqCourseEnum.STUDENT_IDENTITY_SWITCH.getCode());
        body.setClassId(classId);
        body.setStudentId(studentId);
        body.setSwitchType(switchType);
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.COURSE_SYNC.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.CLASS_MESSAGE_KEY + classId);
        ProducerEvent.producerFifoMessage(message);
    }


    /**
     * 解散班级
     *
     * @param classId
     */

    public void disbandClass(Long classId) {
        CourseClassMessageBody body = new CourseClassMessageBody();
        body.setType(RocketMqCourseEnum.DISBAND_CLASS.getCode());
        body.setClassId(classId);
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.COURSE_SYNC.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.CLASS_MESSAGE_KEY + classId);
        ProducerEvent.producerFifoMessage(message);
    }


    /**
     * 解散班级
     *
     * @param classDTO
     * @param list
     */

    public void disbandClassSend(ClassResultDTO classDTO, List<ClassStudentResultDTO> list) {
        if (Objects.isNull(classDTO)) {
            return;
        }
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        List<String> userIds = list.stream().map(item -> Convert.toStr(item.getStudentId())).collect(Collectors.toList());
        String commonInfo = classDTO.getCourseName() + "课程" + classDTO.getName() + "班级";
        TemplateMessageDTO templateMessage = new TemplateMessageDTO();
        templateMessage.setType(SysMessageEnum.DISBAND_CLASS.getCode());
        templateMessage.setClassId(classDTO.getId().toString());
        templateMessage.setFromUserId("0");
        templateMessage.setToUserId(classDTO.getId().toString());
        templateMessage.setTitle("解散班级");
        templateMessage.setContent(commonInfo + "已解散");

        ChatMessageMessageBody body = new ChatMessageMessageBody();
        body.setType(RocketMqRongyunEnum.RONGYUN_SYSTEM_MESSAGE.getCode());
        body.setSenderId("0");
        body.setTargetIds(userIds.toArray(new String[userIds.size()]));
        body.setJson(JSONObject.toJSONString(templateMessage));
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.RONGYUN_MESSAGE.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.SYSTEM_MESSAGE_KEY + classDTO.getId());
        ProducerEvent.producerFifoMessage(message);
    }

    /**
     * 解散班级-变更
     *
     * @param classDTO
     * @param list
     * @author dzy
     */

    public void disbandClassSendNew(ClassResultDTO classDTO, List<ClassStudentResultDTO> list) {
        if (Objects.isNull(classDTO)) {
            return;
        }
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        list = list.stream().filter(v -> Objects.equals(ClassRoleEnum.TEACHER.getCode(), v.getClassRole())
            || Objects.equals(ClassRoleEnum.ASSISTANT.getCode(), v.getClassRole())
            || Objects.equals(YesNoNumberEnum.YES.getCode(), v.getIsRelationalStudent())).collect(Collectors.toList());
        List<String> userIds = list.stream().map(item -> Convert.toStr(item.getStudentId())).collect(Collectors.toList());
        String commonInfo = classDTO.getCourseName() + "课程" + classDTO.getName() + "班级";

        TemplateMessageDTO bean = new TemplateMessageDTO();
        bean.setType(SysMessageEnum.DISBAND_CLASS.getCode());
        bean.setClassId(classDTO.getId().toString());
        bean.setFromUserId("0"); // 0代表系统用户
        bean.setToUserId(classDTO.getId().toString());
        Map<String, Object> content = new HashMap<>();
        content.put("type", SysMessageEnum.DISBAND_CLASS.getCode());
        content.put("title", "解散班级");
        content.put("courseId", classDTO.getCourseId());
        content.put("content", commonInfo + "已解散");
        content.put("end_time", LocalDateTime.now());
        bean.setContent(JSON.toJSONString(content));
        String body = JSON.toJSONString(bean);
        remoteRongyunClient.creatSysUserSend(userIds.toArray(new String[userIds.size()]), body);
    }


    /**
     * 学生加入班级
     *
     * @param classId
     * @param studentId
     */

    public void studentJoinClass(Long classId, Long studentId) {
        CourseClassMessageBody body = new CourseClassMessageBody();
        body.setType(RocketMqCourseEnum.STUDENT_JOIN_CLASS.getCode());
        body.setClassId(classId);
        body.setStudentId(studentId);
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.COURSE_SYNC.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.CLASS_MESSAGE_KEY + classId);
        ProducerEvent.producerFifoMessage(message);
    }

    /**
     * 学生退出班级
     *
     * @param classId
     * @param studentId
     */

    public void studentQuitClass(Long classId, Long studentId, String studentName, Account user) {
        CourseClassMessageBody body = new CourseClassMessageBody();
        body.setType(RocketMqCourseEnum.STUDENT_QUIT_CLASS.getCode());
        body.setClassId(classId);
        body.setStudentId(studentId);
        body.setStudentName(studentName);
        body.setUser(user);
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.COURSE_SYNC.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.CLASS_MESSAGE_KEY + classId);
        ProducerEvent.producerFifoMessage(message);
    }


    /**
     * 添加外部助教
     *
     * @param classId
     * @param userId
     * @param user
     */

    public void addAssistant(Long classId, Long userId, Account user) {
        CourseClassMessageBody body = new CourseClassMessageBody();
        body.setType(RocketMqCourseEnum.ADD_ASSISTANT.getCode());
        body.setClassId(classId);
        body.setStudentId(userId);
        body.setUser(user);
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.COURSE_SYNC.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.CLASS_MESSAGE_KEY + classId);
        ProducerEvent.producerFifoMessage(message);
    }


    /**
     * 被老师拒绝
     *
     * @param classId   班级id
     * @param studentId 学生id
     */

    public void rejectJoinClass(Long classId, Long studentId) {
        CourseClassMessageBody body = new CourseClassMessageBody();
        body.setType(RocketMqCourseEnum.TEACHER_REJECT_JOIN.getCode());
        body.setClassId(classId);
        body.setStudentId(studentId);
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.COURSE_SYNC.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.CLASS_MESSAGE_KEY + classId);
        ProducerEvent.producerFifoMessage(message);
    }

}

